package org.budo.dubbo.protocol.http.aop.permission.user;

import java.io.Serializable;
import java.lang.reflect.Method;

import org.budo.dubbo.protocol.http.authentication.AuthenticationCheckService;
import org.budo.support.spring.context.aware.BudoApplicationContextAware;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class AbstractUserPermissionCheckInterceptor {
    private Boolean defaultUserPermissionCheck = false;

    private AuthenticationCheckService authenticationCheckService;

    private UserPermissionCheckService userPermissionCheckService;

    public UserPermissionCheckService getUserPermissionCheckService() {
        if (null == this.userPermissionCheckService) {
            this.userPermissionCheckService = BudoApplicationContextAware.getBeanCached_2(UserPermissionCheckService.class);
        }

        return this.userPermissionCheckService;
    }

    public AuthenticationCheckService getAuthenticationCheckService() {
        if (null == this.authenticationCheckService) {
            this.authenticationCheckService = BudoApplicationContextAware.getBeanCached_2(AuthenticationCheckService.class);
        }

        return this.authenticationCheckService;
    }

    protected void handlePermissionFailed(Serializable _authenticationPrincipal, String permissionName) {
        this.getUserPermissionCheckService().handlePermissionFailed(_authenticationPrincipal, permissionName);
    }

    protected Boolean hasPermission(Serializable authenticationPrincipal, String permissionName) {
        return this.getUserPermissionCheckService().hasPermission(authenticationPrincipal, permissionName);
    }

    protected String permissionName(Method method) {
        return this.getUserPermissionCheckService().permissionName(method);
    }

    protected void handleAuthFailed(Method method, Serializable authenticationPrincipal) {
        UserPermissionCheckService userPermissionCheckService = this.getUserPermissionCheckService();
        if (null == userPermissionCheckService) {
            log.error("#57 handleAuthFailed, this=" + this + ", method=" + method + ", authenticationPrincipal=" + authenticationPrincipal);
            return;
        }

        userPermissionCheckService.handleAuthFailed(method, authenticationPrincipal);
    }
}